package net.javamine.util.entityUtils.utils;

import java.util.HashMap;
import java.util.Map;

/**
 * 转换数据库类型为java数据类型
 * @author <a href="mailto: java_lht@163.com">Lht</a>
 * @since 2012-11-30
 * @version 1.0
 */
public class TransformDBDataTypeToJavaDataType {
	
	/**
	 * 根据数据库字段类型，得出java数据类型和长度
	 * @param type 数据库字段类型	例：double(5,2); varchar(20)
	 * @return Map<String, String>
	 */
	public static Map<String, String> transformMySQLTypeToJavaTypeAndTypeSize(String type) throws Exception {	
		Map<String, String> map = new HashMap<String, String>();
		
		//获取java数据类型
		String realType = "";
		String size = "";
		if (type.indexOf("(") != -1) {
			realType = type.substring(0, type.indexOf("("));		//例：double(5,2) 中的 double; varchar(20) 中的 varchar
			size = type.substring(type.indexOf("(") + 1, type.indexOf(")"));;		//例：double(5,2) 中的5,2; varchar(20) 中的 20
		} else {
			realType = type;
			size = "";
		}
		String javaType = "";
		if (realType.equals("varchar")) {
			javaType = "String";
		} else if (realType.equals("bigint")) {
			javaType = "long";
		} else if (realType.equals("datetime")) {
			javaType = "Timestamp";
		} else {
			javaType = realType;
		}
		map.put("javaType", javaType);
		
		//获取java数据类型的长度或精度
		
		if (javaType.equals("String")) {
			map.put("stringMaxSize", size);
		} else if (javaType.equals("long") || javaType.equals("int")) {
			map.put("integerMaxSize", size);
			map.put("fractionMaxSize", "0");
		} else if (javaType.equals("double")) {
			String integerMaxSize = size.substring(0, size.indexOf(","));
			String fractionMaxSize = size.substring(size.indexOf(",") + 1, size.length());
			map.put("integerMaxSize", integerMaxSize);
			map.put("fractionMaxSize", fractionMaxSize);
		}
		return map;
	}

}
